﻿using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using Opalis.QuickIntegrationKit;

namespace LocalComputerSecurity
{
    [OpalisObject("Add User to Local Computer Group" , ShowFilters = false)]
    public class AddUserToLocalGroup : IOpalisObject
    {
        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Computer Name");
            designer.AddInput("Local Group Name");
            designer.AddInput("User Name");
            designer.AddInput("Domain").NotRequired();
            designer.AddOutput("Group Name");
            designer.AddOutput("User Name");
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            String computerName = request.Inputs["Computer Name"].AsString();
            String localGroupName = request.Inputs["Local Group Name"].AsString();
            String userName = request.Inputs["User Name"].AsString();
            String domain = request.Inputs["Domain"].AsString();
            try
            {
                DirectoryEntry AD = new DirectoryEntry("WinNT://" + computerName + ",computer");
                if (domain != null)
                {
                    DirectoryEntry Domain = new DirectoryEntry("WinNT://" + domain);
                    DirectoryEntry user = Domain.Children.Find(userName, "User");

                    DirectoryEntry grp = AD.Children.Find(localGroupName, "group");
                    if (grp != null)
                    {
                        grp.Invoke("Add", new object[] { user.Path.ToString() });
                        grp.Close();
                        response.Publish("Group Name", localGroupName);
                        response.Publish("User Name", user.Path.ToString());
                    }
                    else { response.ReportErrorEvent("Failed to find local group", ""); }
                }
                else
                {
                    DirectoryEntry user = AD.Children.Find(userName, "User");

                    DirectoryEntry grp = AD.Children.Find(localGroupName, "group");
                    if (grp != null)
                    {
                        grp.Invoke("Add", new object[] { user.Path.ToString() });
                        grp.Close();
                        response.Publish("Group Name", localGroupName);
                        response.Publish("User Name", user.Path.ToString());
                    }
                    else { response.LogErrorMessage("Failed to find local group"); }
                }
            }
            catch (Exception ex)
            {
                response.LogErrorMessage("Failed to add user to local group\n" + ex.Message.ToString());
            }
        }
    }
}
